
package com.shiku.imserver.common.hander;


import com.shiku.imserver.common.annotation.MessageCommandAnnotation;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public abstract class AbstractMessageHandler
        implements IMessageHandler {
    private Map<Short, Method> handlerMethods;


    public AbstractMessageHandler() {

        init();

    }


    public Map<Short, Method> getHandlerMethods() {

        return this.handlerMethods;

    }


    public void setHandlerMethods(Map<Short, Method> handlerMethods) {

        this.handlerMethods = handlerMethods;

    }


    public void init() {

        this.handlerMethods = new ConcurrentHashMap<>();

        Method[] methods = getClass().getMethods();

        for (Method method : methods) {

            if (method.isAnnotationPresent((Class) MessageCommandAnnotation.class)) {

                MessageCommandAnnotation messageCommandAnnotation = method.<MessageCommandAnnotation>getAnnotation(MessageCommandAnnotation.class);

                if (messageCommandAnnotation != null) {

                    this.handlerMethods.put(Short.valueOf(messageCommandAnnotation.command()), method);

                }

            }

        }

    }


    @Override
    public Method getMessageHandler(short command) {

        return this.handlerMethods.get(Short.valueOf(command));

    }

}


